//
//  PaperItemCellTableView.m
//  DoingPaper
//
//  Created by zhuxuhong on 16/7/25.
//  Copyright © 2016年 zhuxuhong. All rights reserved.
//

#import "PaperItemCellTableView.h"
#import "PaperInputSelectionCell.h"
#import "PaperQuestionOption.h"
#import "PaperOptionWebCell.h"
#import "PaperDataManager.h"
#import "PaperQuestionAnalysisFooter.h"
#import "QuestionContentView.h"
#import "AnswerInputView.h"

@interface PaperItemCellTableView() <UITableViewDelegate,
UITableViewDataSource,UIGestureRecognizerDelegate,
QuestionContentViewDelegate,
AnswerInputViewDelegate>
@property(nonatomic,copy)NSString *paperId;
@end

@implementation PaperItemCellTableView
{
    NSIndexPath *lastSelectedCellIndexPath;
    NSString *baseUrl;
    NSMutableDictionary *sectionViews;
}

-(instancetype)initWithFrame:(CGRect)frame question:(PaperQuestion *)question{
    self = [self initWithFrame:frame];
    
    _question = question;
    baseUrl = [[PaperDataManager sharedManager] paperImagesPathWithId: _question.paperId];
    
    CGFloat bottomInset = 54;
    self.contentInset = UIEdgeInsetsMake(-34, 0, bottomInset, 0);
    
    return self;
}

-(instancetype)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame style:UITableViewStyleGrouped];
    if (self) {
        self.backgroundColor = [UIColor whiteColor];
        self.separatorStyle = UITableViewCellSeparatorStyleNone;
        
        self.delegate = self;
        self.dataSource = self;
        
        sectionViews = [NSMutableDictionary new];
        
        // 单击手势
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(selfDidTap:)];
        tap.numberOfTapsRequired = 1;
        tap.delegate = self;
        [self addGestureRecognizer:tap];
    }
    return self;
}

-(void)endEditing{
    self.editing = false;
}


// 对外方法，查看答案
-(void)setIsScanningAnswer:(BOOL)isScanningAnswer{
    _isScanningAnswer = isScanningAnswer;
    
//    [self reloadData];
}


#pragma mark UITableView

// row height
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    PaperQuestionOption *op = [self questionInSection:indexPath.section].options[indexPath.row];
    return op.contentViewHeight ? op.contentViewHeight : 1;
}

// section number
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return _question.subQuestions.count + 1;
}

// row number
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return [self questionInSection:section].options.count;
}

// header height
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    CGFloat h = [self questionInSection:section].contentViewHeight;
    return h>0 ? h : 1; //!!! 如果是0，则webview不会loadRequest
}

// footer height
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    // 有子题就返回0
    if ([self noNeedInputViewOfQuestionInSection:section]) {
        return 0;
    }
    return 190;
}

// header view
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    QuestionContentView *view = [sectionViews objectForKey:@(section)];
    if (!view) {
        NSString *html = [self questionInSection:section].questionContent;
        QuestionContentView *view = [[QuestionContentView alloc] initWithFrame:CGRectZero viewType:QuestionStem htmlString:html baseUrl:baseUrl atIndexPath:[NSIndexPath indexPathForRow:0 inSection:section]];
        [sectionViews setObject:view forKey:@(section)];
        view.delegate = self;
    }
    return view;
}

// footer view
-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    // 有子题就返回nil
    if ([self noNeedInputViewOfQuestionInSection:section]) {
        return nil;
    }
    AnswerInputView *view = [[AnswerInputView alloc] initWithFrame:CGRectZero];
    view.delegate = self;
    return view;
}

// 不需要输入
-(BOOL)noNeedInputViewOfQuestionInSection: (NSInteger)section{
    PaperQuestion *q = [self questionInSection:section];
    BOOL is = q.subQuestions.count > 0 || [q.qtype isEqualToString:@"1"] || [q.qtype isEqualToString:@"2"] || [q.qtype isEqualToString:@"3"];
    return is;
}

-(PaperQuestion*)questionInSection: (NSInteger)section{
    return section == 0 ? _question : (PaperQuestion*)_question.subQuestions[section-1];
}

// cell for row
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    NSInteger section = indexPath.section;
    PaperQuestion *q = [self questionInSection:section];
    self.allowsSelection = !_question.submited; //已提交卷
    
    // 单选题 / 判断题
    BOOL isSingle = q.qtype && [q.qtype isEqualToString:@"1"];
    BOOL isJudge = q.qtype && [q.qtype isEqualToString:@"3"];
    if (isSingle || isJudge) {
        return [self optionCellOfTableView:tableView atIndexPath:indexPath isSingleOption:true];
    }
    
    // 多选题
    if (q.qtype && [q.qtype isEqualToString:@"2"]) {
        return [self optionCellOfTableView:tableView atIndexPath:indexPath isSingleOption:false];
    }
    
    return nil;
}

#pragma mark - cell
// 单选/多选题/判断题
-(UITableViewCell*)optionCellOfTableView: (UITableView*)tableView
                           atIndexPath: (NSIndexPath *)indexPath
                        isSingleOption: (BOOL)single{
    static NSString *reuseId = @"PaperOptionWebCell";
    PaperOptionWebCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseId];
    PaperQuestionOption *op = _question.options[indexPath.row];
    if (!cell) {
        cell = [[PaperOptionWebCell alloc]initWithReuseIdentifier:reuseId contentViewDelegate:self contentString:op.optionContent baseUrl:baseUrl isSingleOption:single atIndexPath:indexPath];
    }
    
    // 设置选中项
    for (NSNumber *op in _question.userOptions) {
        cell.choosed = [op integerValue] == indexPath.row ? true : false;
    }
    return cell;
}

#pragma mark - 选中逻辑
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if ([_question.qtype isEqualToString:@"1"] || [_question.qtype isEqualToString:@"3"]) {
        [self singleCellOfTableView:tableView didSelectAtIndexPath:indexPath];
    }
    else if ([_question.qtype isEqualToString:@"2"]) {
        [self multiCellOfTableView:tableView didSelectAtIndexPath:indexPath];
    }
}

// 单选题选中一个
-(void)singleCellOfTableView: (UITableView*)tableView
        didSelectAtIndexPath:(NSIndexPath *)indexPath{
    if (lastSelectedCellIndexPath) {
        PaperOptionWebCell *lastCell = [tableView cellForRowAtIndexPath:lastSelectedCellIndexPath];
        lastCell.choosed = false;
    }
    // 选中项
    [tableView deselectRowAtIndexPath:indexPath animated:true];
    PaperOptionWebCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    cell.choosed = true;
    lastSelectedCellIndexPath = indexPath;
    
    [_question.userOptions removeAllObjects];
    [_question.userOptions addObject:@(lastSelectedCellIndexPath.row)];
    
    NSLog(@"userOptions: %@",_question.userOptions);
    
    [self nextQuestion];
}

-(void)nextQuestion{
    // 下一页
    [[NSNotificationCenter defaultCenter]postNotificationName:@"DidSelectOptionNoti" object:nil];
}

// 多选题
-(void)multiCellOfTableView: (UITableView*)tableView
        didSelectAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:true];
    PaperOptionWebCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    cell.choosed = !cell.choosed;
    cell.choosed ? [_question.userOptions addObject:@(indexPath.row)] : [_question.userOptions removeObject:@(indexPath.row)];
    NSLog(@"userOptions: %@",_question.userOptions);
}

// 单击手势，结束输入
-(void)selfDidTap: (UITapGestureRecognizer*)tap{
    for (UIView *sub in self.subviews) {
        if ([sub isMemberOfClass:[AnswerInputView class]]) {
            [sub endEditing:true];
        }
    }
}

#pragma mark - UIGestureRecognizerDelegate
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch
{
    if ([touch.view isKindOfClass:[self class]]) {
        return true;
    }
    return false;
}


#pragma mark - QuestionContentViewDelegate
-(void)questionContentView:(QuestionContentView *)view
                  viewType:(QuestionContentViewType)type
    contentDidLoadWithViewHeight:(CGFloat)height
                 indexPath:(NSIndexPath *)indexPath{
    
    NSInteger section = indexPath.section;
    if (type == QuestionStem) { //题干
        [self questionInSection:section].contentViewHeight = height;
    }
    else{ // 选项
        NSInteger row = indexPath.row;
        PaperQuestionOption *op = [self questionInSection:section].options[row];
        op.contentViewHeight = height + 20;
    }
    [self reloadData];
}

#pragma mark - AnswerInputViewDelegate
-(void)answerInputViewDidEndInputWithReturnKeyClick{
    [self nextQuestion];
}

-(void)answerInputView:(AnswerInputView *)inputView sectionIndex:(NSInteger)section didEndInputWithInputText:(NSString *)text{
    PaperQuestion *q = [self questionInSection:section];
    q.userAnswer = text;
}

-(void)answerInputView:(AnswerInputView *)inputView sectionIndex:(NSInteger)section didEndInputWithInputImage:(UIImage *)image{
    PaperQuestion *q = [self questionInSection:section];
    q.userAnswerImage = image;
}
@end
